/*
 * AmbienteWorker.cpp
 *
 *  Created on: 26-10-2011
 *      Author: cristian
 */

#include "AmbienteWorker.h"


AmbienteWorker::~AmbienteWorker() {

}

void AmbienteWorker::setNodoAndRun(unsigned int x, unsigned int y, Worker *nodo)
{
	this->setNodo(x,y,nodo);


	nodo->newPos(x,y);

	list<Worker*>::iterator pos = this->getWorkers().begin();

	int rc = pthread_create((*pos)->getThread(), (*pos)->getAttr(), Worker::start, (*pos));

}


void AmbienteWorker::runAll()
{

		list<Worker*>::iterator pos = this->getWorkers().begin();

		while (pos != this->getWorkers().end()) {
			pthread_create((*pos)->getThread(), (*pos)->getAttr(), Worker::start, (*pos));
			pos++;
		}
}

unsigned int AmbienteWorker::x()
{
	return getX();
}



unsigned int AmbienteWorker::y()
{
	return getY();
}

Worker* AmbienteWorker::getWorker(unsigned int x, unsigned int y)
{
	return getNodo(x,y);
}



bool AmbienteWorker::move(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2)
{

	if (x2 < this->getX() && y2 < this->getY() && x2>=0 && y2 >=0){

		if (this->getNodo(x2,y2) == NULL ){

			    this->setNodo(x2,y2,this->getNodo(x1,y1));
				this->setNodo(x1,y1,NULL);

				pthread_mutex_unlock(&mutex);

				 return true;
		}else{
			Worker* worker = this->getNodo(x2,y2);
			//TODO Merge Workers.
		}

	}
	return false;
}










